// 页面元素
const uploadArea = document.getElementById('uploadArea');
const fileInput = document.getElementById('fileInput');
const uploadBtn = document.getElementById('uploadBtn');
const submitBtn = document.getElementById('submitBtn');
const loading = document.getElementById('loading');
const resultsSection = document.getElementById('resultsSection');
const resultsList = document.getElementById('resultsList');

let selectedFile = null;

// 事件监听器
uploadArea.addEventListener('click', () => fileInput.click());
uploadBtn.addEventListener('click', () => fileInput.click());
fileInput.addEventListener('change', handleFileSelect);
submitBtn.addEventListener('click', submitForRecognition);

// 拖拽上传功能
uploadArea.addEventListener('dragover', (e) => {
    e.preventDefault();
    uploadArea.style.borderColor = '#2980b9';
    uploadArea.style.backgroundColor = '#f8f9fa';
});

uploadArea.addEventListener('dragleave', () => {
    uploadArea.style.borderColor = '#3498db';
    uploadArea.style.backgroundColor = '';
});

uploadArea.addEventListener('drop', (e) => {
    e.preventDefault();
    uploadArea.style.borderColor = '#3498db';
    uploadArea.style.backgroundColor = '';
    
    if (e.dataTransfer.files.length) {
        handleFileSelection(e.dataTransfer.files[0]);
    }
});

// 处理文件选择
function handleFileSelect(e) {
    if (e.target.files.length) {
        handleFileSelection(e.target.files[0]);
    }
}

// 处理文件选择逻辑
function handleFileSelection(file) {
    if (!file.type.match('image.*')) {
        alert('请选择图片文件！');
        return;
    }
    
    selectedFile = file;
    submitBtn.disabled = false;
    
    // 显示文件名
    const fileName = file.name;
    uploadArea.innerHTML = `<p>已选择文件: ${fileName}</p>`;
}

// 提交识别请求
async function submitForRecognition() {
    if (!selectedFile) {
        alert('请先选择图片文件！');
        return;
    }
    
    // 显示加载状态
    loading.style.display = 'block';
    resultsSection.style.display = 'none';
    
    try {
        // 将图片转换为base64
        const base64Image = await fileToBase64(selectedFile);
        
        // 调用后端Logo识别API
        const result = await recognizeLogo(base64Image);
        
        // 显示结果
        displayResults(result, base64Image);
    } catch (error) {
        console.error('识别过程中出错:', error);
        alert('识别过程中出现错误，请重试。');
    } finally {
        loading.style.display = 'none';
    }
}

// 将文件转换为base64编码
function fileToBase64(file) {
    return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.onload = () => {
            // 移除data URL前缀，只保留base64部分
            const base64 = reader.result.split(',')[1];
            resolve(base64);
        };
        reader.onerror = reject;
        reader.readAsDataURL(file);
    });
}

// 调用Logo识别API（通过后端）
async function recognizeLogo(imageBase64) {
    try {
        const response = await fetch('/api/recognize_logo', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ image: imageBase64 })
        });
        
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        
        return await response.json();
    } catch (error) {
        console.error('API调用错误:', error);
        throw error;
    }
}

// 显示识别结果
function displayResults(data, imageBase64 = null) {
    resultsList.innerHTML = '';
    
    if (data.error) {
        resultsList.innerHTML = `<p class="error">错误: ${data.error}</p>`;
        resultsSection.style.display = 'block';
        return;
    }
    
    if (!data.result || data.result.length === 0) {
        resultsList.innerHTML = '<p class="no-results">未识别到任何Logo</p>';
        resultsSection.style.display = 'block';
        return;
    }
    
    data.result.forEach((item, index) => {
        const resultItem = document.createElement('div');
        resultItem.className = 'result-item';
        
        // 如果有裁切图像数据，则使用，否则显示占位符
        const logoImage = item.cropped_image_base64 ? 
            `<img src="data:image/jpeg;base64,${item.cropped_image_base64}" alt="Logo">` : 
            '<div class="placeholder">无预览</div>';
        
        // 为商标名称添加链接（点击显示模态框）
        const trademarkLink = item.name ? 
            `<a href="#" onclick="showTrademarkDetails('${encodeURIComponent(item.name)}', '${imageBase64 || ''}'); return false;">${item.name}</a>` : 
            (item.name || '未知品牌');
        
        resultItem.innerHTML = `
            <div class="logo-image">
                ${logoImage}
            </div>
            <div class="result-info">
                <h3>${trademarkLink} <span class="view-details">[<<查看详情]</span></h3>
                <div class="similarity">相似度: <span>${(item.probability * 100).toFixed(2)}%</span></div>
            </div>
        `;
        
        resultsList.appendChild(resultItem);
    });
    
    resultsSection.style.display = 'block';
}

// 显示商标详情模态框（增强版，支持图片搜索）
function showTrademarkDetails(name, imageBase64 = '') {
    // 如果有图片数据，则使用新的联合搜索API
    if (imageBase64) {
        searchTrademarkWithImage(name, imageBase64);
    } else {
        // 否则使用原来的文本搜索
        originalShowTrademarkDetails(name);
    }
}

// 原始的显示商标详情函数
function originalShowTrademarkDetails(name) {
    trademarkName = name;
    modal.style.display = "block";
    
    // 清除之前的数据
    clearCache();
    document.getElementById('modalTrademarkList').innerHTML = '';
    document.getElementById('modalTrademarkList').style.display = 'none';
    document.getElementById('modalError').style.display = 'none';
    document.getElementById('modalLoading').style.display = 'block';
    
    // 加载商标数据
    loadTrademarks(1);
}

// 使用图片和名称联合搜索商标
async function searchTrademarkWithImage(name, imageBase64) {
    modal.style.display = "block";
    
    // 清除之前的数据
    clearCache();
    document.getElementById('modalTrademarkList').innerHTML = '';
    document.getElementById('modalTrademarkList').style.display = 'none';
    document.getElementById('modalError').style.display = 'none';
    document.getElementById('modalLoading').style.display = 'block';
    
    try {
        // 调用新的API端点，同时使用图片和名称搜索
        const response = await fetch('/api/search_trademark_with_image', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                name: name,
                image: imageBase64,
                top_k: 40
            })
        });
        
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        
        const trademarkData = await response.json();
        
        // 检查API响应结构
        if (trademarkData.code !== 200) {
            throw new Error(trademarkData.message || 'API调用失败');
        }
        
        // 验证数据结构
        if (!trademarkData.data) {
            throw new Error('API响应缺少data字段');
        }
        
        // 检查是否有结果
        if (!trademarkData.data.result || trademarkData.data.result === "") {
            // 没有结果的情况
            allTrademarks = [];
            hasMore = false;
            currentPage = 1;
            displayTrademarks();
            return;
        }
        
        // 获取商标列表
        const trademarks = Array.isArray(trademarkData.data.result.list) ? trademarkData.data.result.list : [];
        
        // 只保留状态为"已注册"的商标
        const registeredTrademarks = trademarks.filter(trademark => {
            // 检查多种可能的已注册状态表示
            const status = trademark.status || '';
            return status.includes('已注册') || status.includes('已注冊') || status === '已注册' || status === '已注冊';
        });
        
        // 设置缓存
        allTrademarks = registeredTrademarks;
        hasMore = false; // 对于图片搜索，我们只获取一次结果
        currentPage = 1;
        
        // 显示商标数据
        displayTrademarks();
    } catch (error) {
        console.error('获取商标信息失败:', error);
        document.getElementById('modalError').textContent = '获取商标信息失败: ' + error.message;
        document.getElementById('modalError').style.display = 'block';
        document.getElementById('modalLoading').style.display = 'none';
    } finally {
        document.getElementById('modalLoading').style.display = 'none';
        document.getElementById('modalLoadingMore').style.display = 'none';
    }
}